<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { getUserPage, reqAddUser, reqUpdateUser } from '@/api/product/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Action } from 'element-plus'
//收集数据的数组
let userParams = reactive<any>({
  username: '',
  name: '',
  phone: '',
  sex: '1',
  idNumber: '',
  updateUser: '',
  createUser: '',
  password: '',
  status: '',
  createTime: '',
  updateTime: '',
  id: '',
})
//控制对话框显示或者隐藏
let dialogFormVisible = ref(false)
//当前页码
let pageNo = ref<number>(1)
//每页条数
let limit = ref<number>(10)
// 存储一下已有品牌数据的总数
let total = ref<number>(0)
//存储数据
let dishArr = ref<any>([])
// 获取已有品牌的接口封装为一个函数
const getDish = async () => {
  let result = await getUserPage(pageNo.value, limit.value)
  console.log(result)
  if (result.code == 1) {
    //存储总个数
    total.value = result.data.total
    dishArr.value = result.data.records
  }
}
//分页器页码发生变化时候触发
const changePageNo = () => {
  //当前页码发生变化的时候，再次发请求，获取数据
  getDish()
}
//当下拉菜单发生变化的时候，会触发此方法
const sizeChange = () => {
  pageNo.value = 1
  getDish()
}
//发送请求，组件一挂载
onMounted(() => {
  getDish()
})

//添加user的方法
const addUser = () => {
  dialogFormVisible.value = true
  //收集数据清空
  userParams.createUser = ''
  userParams.updateUser = ''
  userParams.username = ''
  userParams.name = ''
  userParams.phone = ''
  userParams.idNumber = ''
  userParams.sex = '1'
  userParams.id = ''
  userParams.status = ''
  userParams.updateTime = ''
  userParams.createTime = ''
  userParams.password = ''
}
//修改user的方法
// row : 当前已经有点品牌
const updateUser = (row: any) => {
  dialogFormVisible.value = true
  console.log(row)
  //复制展示
  userParams.updateUser = row.updateUser
  userParams.createUser = row.createUser
  userParams.username = row.username
  userParams.name = row.name
  userParams.phone = row.phone
  userParams.idNumber = row.idNumber
  userParams.sex = row.sex
  userParams.id = row.id
  userParams.updateTime = row.updateTime
  userParams.createTime = row.createTime
  userParams.status = row.status
  userParams.password = row.password
}
//对话框的取消按钮
const cancle = () => {
  dialogFormVisible.value = false
}
//对话框的确定按钮
const confirm = async () => {
  if (userParams.createUser == null) {
    userParams.createUser = localStorage.getItem('token')
  }
  userParams.updateUser = localStorage.getItem('token')
  // 判断是否是新增还是 增加
  if (userParams.updateTime == null) {
    let result = await reqAddUser(userParams)
    if (result.code == 1) {
      //添加用户成功
      dialogFormVisible.value = false
      //弹出提示
      ElMessage({
        type: 'success',
        message: '添加用户成功',
      })
      //发起请求
      getDish()
      //收集数据清空
    } else {
      //失败
      ElMessage({
        type: 'error',
        message: '添加用户失败',
      })
      dialogFormVisible.value = false
    }
  } else {
    let result = await reqUpdateUser(userParams)
    if (result.code == 1) {
      //添加用户成功
      dialogFormVisible.value = false
      //弹出提示
      ElMessage({
        type: 'success',
        message: '更新用户成功',
      })
      //发起请求
      getDish()
    } else {
      //失败
      ElMessage({
        type: 'error',
        message: '更新用户失败',
      })
      dialogFormVisible.value = false
    }
  }
}
//表单自定义校验规则
const validatorUserName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('名称不低于2位'))
  }
}
const validatorUserPhone = (rule: any, value: any, callBack: any) => {
  if (value.trim().length == 11) {
    callBack()
  } else {
    callBack(new Error('手机号不对'))
  }
}
const validatorUserIdnumber = (rule: any, value: any, callBack: any) => {
  if (value.trim().length == 18) {
    callBack()
  } else {
    callBack(new Error('身份证号不对'))
  }
}
//表单校验规则对象
//required:必须校验, brigger: 出发校验时机
const rules = {
  username: [{ required: true, trigger: 'blur', validator: validatorUserName }],
  name: [{ required: true, trigger: 'blur', validator: validatorUserName }],
  phone: [{ required: true, trigger: 'blur', validator: validatorUserPhone }],
  idNumber: [
    { required: true, trigger: 'blur', validator: validatorUserIdnumber },
  ],
}
//是否禁用的弹出确定框
const open = (row: any) => {
  let message = row.status == 0 ? '是否启用' : '是否禁用'
  ElMessageBox.alert(message, '修改状态', {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: '确定',
    callback: (action: Action) => {
      if (action == 'cancel') {
        ElMessage({
          type: 'info',
          message: '取消',
        })
      } else {
        //调用修改状态的方法
        changeUserStatus(row)
      }
    },
  })
}
// 修改个人状态的方法
const changeUserStatus = (row: any) =>{
  //赋值
  userParams.updateUser = localStorage.getItem('token')
  userParams.createUser = row.createUser
  userParams.username = row.username
  userParams.name = row.name
  userParams.phone = row.phone
  userParams.idNumber = row.idNumber
  userParams.sex = row.sex
  userParams.id = row.id
  userParams.updateTime = row.updateTime
  userParams.createTime = row.createTime
  userParams.status = row.status == 1 ? 0 : 1
  userParams.password = row.password
  confirm()
}
</script>

<template>
  <div class="-container">
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- card body -->
      <!-- 顶部的设置按钮 -->
      <el-button type="primary" size="default" icon="Plus" @click="addUser">
        添加
      </el-button>
      <!-- 表格组件用户展示已经有的菜品 -->
      <el-table :data="dishArr" style="margin: 20px 0px">
        <el-table-column label="员工姓名" prop="name"></el-table-column>
        <el-table-column label="账号名称" prop="username"></el-table-column>
        <el-table-column label="手机号" prop="phone"></el-table-column>
        <el-table-column label="账号状态" prop="status">
          <template #="{ row, $index }">
            <text>{{ row.status == 1 ? '启用' : '禁用' }}</text>
          </template>
        </el-table-column>
        <el-table-column label="最后操作时间">
          <template #="{ row, $index }">
            <text style="color: rgb(108, 200, 239)">{{ row.updateTime }}</text>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              circle
              @click="updateUser(row)"
            />
            <el-button
              :type="row.status == '0' ? '' : 'danger'"
              size="small"
              circle
              @click="open(row)"
            >
              {{ row.status == '0' ? '启用' : '禁用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件
       v-model:current-page :设置当前的分页器页码
       v-model:page-size : 展示条数每一页
       :page-sizes :设置下拉框的选择条数
       layout ：分页器的六个子组件的位置调整
      -->
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="sizeChange"
        @current-change="changePageNo"
      />
    </el-card>
    <!-- 对话框组件：添加新的员工 -->
    <!-- v-model:控制对话框是否隐藏
        title 设置左上角标题
    -->
    <el-dialog
      :title="userParams.updateTime == null ? '添加员工' : '更新员工'"
      v-model="dialogFormVisible"
    >
      <el-form
        :inline="false"
        size="normal"
        label-width="20%"
        :model="userParams"
        :rules="rules"
      >
        <el-form-item label="账号名称" prop="username">
          <el-input
            v-model="userParams.username"
            placeholder="输入账号名称"
            size="normal"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="员工姓名" prop="name">
          <el-input
            v-model="userParams.name"
            placeholder="输入员工名称"
            size="normal"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" size="normal" prop="phone">
          <el-input
            placeholder="输入手机号"
            size="normal"
            clearable
            v-model="userParams.phone"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" size="normal">
          <el-radio-group v-model="userParams.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="身份证号" size="normal" prop="idNumber">
          <el-input
            v-model="userParams.idNumber"
            placeholder="输入身份证号"
            size="normal"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 具名插槽 -->
      <template #footer>
        <el-button type="primary" size="default" @click="cancle">
          取消
        </el-button>
        <el-button type="primary" size="default" @click="confirm">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped></style>
